<script lang="ts" setup>
import { message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import type { UnwrapRef } from 'vue';
import { useRoute } from 'vue-router';
// 获取数据
const sheetname = ref<string>('');
const date = ref<string>('');
const loading = ref<boolean>(false);
const columns = ref<any[]>([]);
const data = ref<any[]>([]);
const header = ref<any[]>([]);
const flag = ref<boolean>(true);

async function getquarterData() {
  loading.value = true;
  // 获取数据
  await getQuarterListByYearMonth(date.value).then((res: any) => {
    const alldata: any[] = res.data;
    data.value = alldata.filter(record => record.sheetName === sheetname.value);
    if (data.value.length === 0) {
      flag.value = false;
    }
  }).finally(() => {
    loading.value = false;
  });

  // 处理数据
  for (let i = 0; i < data.value.length; i++) {
    if (data.value[i].isField === 'true') {
      const headerdata = Object.keys(data.value[i])
        .filter(key => (key.startsWith('generalField') || key.startsWith('isField') || key.startsWith('id')) && data.value[i][key] !== '')
        .reduce((acc: any, key) => {
          acc[key] = data.value[i][key];
          return acc;
        }, {});
      header.value.push(headerdata);
    }
  }
}
const oldheader = ['generalFieldA', 'generalFieldB', 'generalFieldC', 'generalFieldD', 'generalFieldE', 'generalFieldF', 'generalFieldG', 'generalFieldH', 'generalFieldI', 'generalFieldJ', 'generalFieldK', 'generalFieldL', 'generalFieldM', 'generalFieldN', 'generalFieldO'];
function getColumns() {
  loading.value = true;
  const header1 = header.value[0];
  const hlength = Object.keys(header1).length;
  for (let i = 0; i < hlength - 2; i++) {
    columns.value.push({
      dataIndex: oldheader[i],
      align: 'center',
    });
  }
  columns.value.push({
    dataIndex: 'operation',
    align: 'center',
    width: 150,
  });
  loading.value = false;
}

onMounted(async () => {
  sheetname.value = useRoute().query.assessmentMethod as string;
  date.value = useRoute().query.date as string;
  await getquarterData().then(() => {
    getColumns(); // 确保在数据获取后调用 getHeaderData
  });
});
// 编辑
const editableData: UnwrapRef<Record<string, any>> = reactive({});
function edit(id: number) {
  editableData[id] = cloneDeep(data.value.find(item => item.id === id));
}
async function save(id: number) {
  const index = data.value.findIndex(item => item.id === id);
  if (index !== -1) {
    const newData = { ...data.value[index], ...editableData[id] };
    data.value[index] = newData;
    await updateQuarterHistoryRecord(newData).then(() => {
      message.success('修改成功!');
      delete editableData[id];
    });
  }
}
function cancel(id: number) {
  delete editableData[id];
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            季度-历史记录详情：{{ sheetname }}
          </div>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button type="primary" @click="$router.push('/assessment_indicators/quarter/history')">
            返回
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-table
        v-if="flag" :columns="columns" :data-source="data" row-key="id" :scroll="{ x: 1024 }" class="q-table"
        :pagination="false" bordered :show-header="false"
      >
        <template #bodyCell="{ record, column, text }: { record: any, column: any, text: any }">
          <template v-if="column?.dataIndex?.startsWith('general') && record.isField === 'false'">
            <div>
              <a-input
                v-if="editableData[record.id]"
                v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
              />
              <template v-else>
                {{ record[column?.dataIndex as string] }}
              </template>
            </div>
          </template>
          <div v-if="column && record.isField === 'false'">
            <template v-if="column.dataIndex === 'operation'">
              <div class="editable-row-operations">
                <span v-if="editableData[record.id]">
                  <a-typography-link @click="save(record.id)">保存</a-typography-link>
                  <a @click="cancel(record.id)">取消</a>
                </span>
                <span v-else>
                  <a @click="edit(record.id)">编辑</a>
                </span>
              </div>
            </template>
          </div>
          <template v-else-if="record.isField === 'true'">
            <div class="table-title">
              <p>{{ text }}</p>
            </div>
          </template>
        </template>
      </a-table>
      <div v-else>
        <a-empty />
      </div>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 31px;
    margin-bottom: 10px;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    height: 100%;
    overflow: auto;

    .m-collapse {
      max-height: 460px;
      overflow-y: auto;
    }
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
